package com.lyfy.sd.order.controller;

import com.lyfy.sd.order.dao.entity.OrderMaster;
import com.lyfy.sd.order.dao.mapper.OrderMasterMapper;
import com.lyfy.sd.order.vo.RespVo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.lyfy.sd.order.constant.Constant.DEFAULT_CREATOR;
import static com.lyfy.sd.order.constant.Constant.DEFAULT_USER_ID;

/**
 * @author: 谢星星
 * @date: 2022/10/3 01:09
 * @description:
 */
@RestController
public class SdReadWriteController {

    @Resource
    private OrderMasterMapper orderMasterMapper;

    /**
     * 场景：测试插入数据时，数据不会插入到读库中
     */
    @GetMapping(value = "rw/insert", produces = MediaType.APPLICATION_JSON_VALUE)
    public RespVo rwInsert() {
        Date now = new Date();
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderMasterId(RandomUtils.nextLong());
        orderMaster.setUserId(now.getTime());
        orderMaster.setCreateD(now);
        orderMaster.setUpdateD(now);
        orderMaster.setCreator(DEFAULT_CREATOR);
        orderMaster.setOrderStatus(1);
        orderMaster.setPayStatus(1);
        orderMaster.setUpdator(DEFAULT_CREATOR);
        orderMaster.setModifyD(now);
        orderMasterMapper.insert(orderMaster);
        return RespVo.SUCCESS();
    }


    /**
     * 场景：测试查询数据时，会使用轮询方式从读写库中读取数据
     */
    @GetMapping(value = "rw/select", produces = MediaType.APPLICATION_JSON_VALUE)
    public RespVo rwrSelect() {
        List<OrderMaster> orderMasterList = orderMasterMapper.selectByExample(Example.builder(OrderMaster.class)
                .andWhere(WeekendSqls.<OrderMaster>custom().andEqualTo(OrderMaster::getUserId, DEFAULT_USER_ID))
                .build());

        return RespVo.SUCCESS(orderMasterList);
    }

    /**
     * 场景：测试查询数据时，且开启事务时，查询只会从写库读取数据
     */
    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
    @GetMapping(value = "rw/select-tx", produces = MediaType.APPLICATION_JSON_VALUE)
    public RespVo rwwSelect() {
        List<OrderMaster> orderMasterList = orderMasterMapper.selectByExample(Example.builder(OrderMaster.class)
                .andWhere(WeekendSqls.<OrderMaster>custom().andEqualTo(OrderMaster::getUserId, DEFAULT_USER_ID))
                .build());

        return RespVo.SUCCESS(orderMasterList);
    }
}
